<template>
    <el-card class="login">
        <el-form ref="form" label-width="70px"  :inline="true"  :rules="rules" :model="form">
        <h3>系统登录</h3>
        <el-form-item  label="用户名"  prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
        </el-form>
    </el-card>
    
</template>

<script>
import Cookie from "js-cookie"
import {logInApi} from '@/api'
export default {
    data () {
        return {
            form: {
                username: '',
                password: '',
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名'}
                ],
                password: [
                    { required: true, message: '请输入密码'}
                ]
            }
        }
    },
    methods: {
        onSubmit() {
            this.$refs.form.validate((valid) => { 
                // 校验通过valid返回true
                if(valid) {
                    logInApi(this.form).then(({data}) => {
                        if(data.code === 200) {
                            console.log(data);
                            const token = data.data.token;
                            // 存入token
                            Cookie.set('token', token);

                            // 从后端获取菜单数据，存入store中
                            this.$store.commit("setMenu", data.data.menu);
                            // 从获取route实例，传入store
                            this.$store.commit("addMenu", this.$router);
                            console.log(this.$router);

                            // 提示登录成功并跳转
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            });
                            this.$router.push("/home");
                        } else {
                            this.$message.error(data.data.message);
                        }
                    })
                }
            })

        }
    }

}
</script>
 
<style lang = "less" scoped>
    .login {
        width: 350px;
        margin: 100px auto;
        text-align: center;
        h3 {
            margin-bottom: 20px;
        }
        
    }
</style>